package org.rcgwt.client.ui.validator.impl;

import java.util.Map;

import org.rcgwt.client.ui.validator.IMasker;
import org.rcgwt.client.util.PatternBuilder;

public class DefaultMasker implements IMasker {

	private static final char REPLACED_BY_CHARACTER = '_';
	private char replacedBy;

	private String pattern;

	public DefaultMasker(Map<String, String> parameters) {
		replacedBy = REPLACED_BY_CHARACTER;

		if (parameters.containsKey("replaced-by")) {
			if (parameters.get("replaced-by").length() == 1) {
				replacedBy = PatternBuilder.encode("%%1",
						parameters.get("replaced-by")).charAt(0);
			}
		}
		if (parameters.containsKey("pattern")) {
			pattern = parameters.get("pattern");
		}
	}

	public Boolean[] getEditablePositions() {
		Boolean[] editablePositions = new Boolean[pattern.length()];
		for (int i = 0; i < pattern.length(); i++) {
			char c = pattern.charAt(i);
			editablePositions[i] = (c == replacedBy);
		}
		return editablePositions;
	}

	public boolean isEditablePosition(int pos) {
		if (pos >= getEditablePositions().length) {
			if (pos == getEditablePositions().length) {
				pos--;
			} else {
				return false;
			}
		}
		return getEditablePositions()[pos];
	}

	@Override
	public int getFirstEditablePosition() {
		for (int i = 0; i < getEditablePositions().length; i++) {
			if (getEditablePositions()[i] == true) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public int getLastEditablePosition() {
		int lep = -1;
		for (int i = 0; i < getEditablePositions().length; i++) {
			if (getEditablePositions()[i] == true) {
				lep = i;
			}
		}
		return lep;
	}

	@Override
	public int getNextEditablePosition(int pos) {
		if (pos >= getEditablePositions().length || pos < 0) {
			if (pos == getEditablePositions().length) {
				pos--;
			} else {
				return -1;
			}
		}
		for (int i = pos; i < getEditablePositions().length; i++) {
			if (getEditablePositions()[i] == true) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public int getPreviousEditablePosition(int pos) {
		if (pos >= getEditablePositions().length || pos < 0) {
			if (pos == getEditablePositions().length) {
				pos--;
			} else {
				return -1;
			}
		}
		for (int i = pos; i >= 0; i--) {
			if (getEditablePositions()[i] == true) {
				return i;
			}
		}
		return -1;
	}

	public char getReplacedBy() {
		return replacedBy;
	}

	public void setReplacedBy(char replacedBy) {
		this.replacedBy = replacedBy;
	}

	public String getPattern() {
		return pattern;
	}

	public void setPattern(String pattern) {
		this.pattern = pattern;
	}

	@Override
	public String toString() {
		return "MaskerImpl [pattern=" + pattern + ", replacebyChar="
				+ replacedBy + "]";
	}
}
